package com.xray.netdisk.ui;

import com.xray.netdisk.utils.NetworkUtilsV2;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * 登录窗体
 */
public class LoginForm {
    private JTextField txtUsername;
    private JTextField txtPassword;
    private JButton btLogin;
    private JButton btExit;
    private JPanel panel1;
    private static JFrame frame;


    public LoginForm() {
        //点击登录
        btLogin.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if(txtUsername.getText().isEmpty()){
                    JOptionPane.showMessageDialog(null,"需要填写账号");
                    return;
                }
                if(txtPassword.getText().isEmpty()){
                    JOptionPane.showMessageDialog(null,"需要填写密码");
                    return;
                }
                //服务器登录验证
                Long userId = NetworkUtilsV2.login(txtUsername.getText(), txtPassword.getText());
                if(userId == -1){
                    JOptionPane.showMessageDialog(null,"账号或密码错误");
                    return;
                }
                System.out.println(userId);
                //将用户id传递到客户端窗体
                ClientForm clientUI = new ClientForm();
                clientUI.refreshFileList(userId);
                //显示客户端窗体
                showFrame("ClientUI",clientUI.panel1,600,400);
                //当前窗体关闭
                frame.dispose();
            }
        });

        btExit.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });
    }

    /**
     * 显示窗体
     * @param formName
     * @param contentPane
     * @param width
     * @param height
     * @return
     */
    public static JFrame showFrame(String formName,JPanel contentPane,int width,int height){
        JFrame frame = new JFrame(formName);
        frame.setContentPane(contentPane);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setSize(width,height);
        frame.setVisible(true);
        return frame;
    }

    public static void main(String[] args) {
        frame = showFrame("LoginFrame",new LoginForm().panel1,400,300);
    }

}
